const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 1234 });
const clients = new Set();

wss.on('connection', (ws) => {
  console.log('新客户端连接');
  clients.add(ws);

  ws.on('message', (message) => {
    // 广播消息给所有其他客户端
    for (const client of clients) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(message.toString());
      }
    }
  });

  ws.on('close', () => {
    console.log('客户端断开连接');
    clients.delete(ws);
  });

  ws.on('error', (error) => {
    console.error('WebSocket 错误:', error);
  });
});

console.log('WebSocket 服务器运行在 ws://localhost:1234');